<template>
  <div id="cesiumContainer" style="width: 100%; height: 100vh">
    <div class="control-panel">
      <button @click="toggleConnection" :class="{ 'connected': isConnected }">
        {{ isConnected ? '断开连接' : '连接服务器' }}
      </button>
      <div class="status">
        状态: {{ isConnected ? '已连接' : '未连接' }}
      </div>
      <div class="aircraft-list">
        <h4>飞机列表:</h4>
        <div v-for="aircraft in aircrafts" :key="aircraft.id" class="aircraft-item">
          <span>{{ aircraft.name }}</span>
          <span class="position">{{ aircraft.position }}</span>
        </div>
      </div>
      <div class="info">
        总飞机数: {{ Object.keys(aircrafts).length }}<br>
        轨迹点数: {{ totalTrackPoints }}<br>
        实体数: {{ aircraftEntities.size }}
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "MapTrack",
  data() {
    return {
      viewer: null,
      aircraftEntities: new Map(), // 存储多架飞机实体
      trackEntities: new Map(), // 存储多条轨迹线实体
      ws: null,
      isConnected: false,
      aircrafts: {}, // 存储飞机数据
      totalTrackPoints: 0,
      // WebSocket 服务器地址
      wsUrl: 'ws://127.0.0.1:6088/uam/v2/ws/uam/channel/245'
    };
  },
  mounted() {
    console.log('MapTrack 组件已挂载');
    this.loadCesiumAndInit();
  },
  beforeUnmount() {
    this.disconnectWebSocket();
    if (this.viewer) {
      this.viewer.destroy();
    }
  },
  methods: {
    loadCesiumAndInit() {
      // 动态加载 Cesium
      if (window.Cesium) {
        console.log('Cesium 已加载，开始初始化...');
        this.initCesium();
      } else {
        console.log('正在加载 Cesium...');
        
        // 加载 Cesium CSS
        const link = document.createElement('link');
        link.rel = 'stylesheet';
        link.href = 'https://cesium.com/downloads/cesiumjs/releases/1.132/Build/Cesium/Widgets/widgets.css';
        document.head.appendChild(link);
        
        // 加载 Cesium JS
        const script = document.createElement('script');
        script.src = 'https://cesium.com/downloads/cesiumjs/releases/1.132/Build/Cesium/Cesium.js';
        script.onload = () => {
          console.log('Cesium 加载完成');
          this.initCesium();
        };
        script.onerror = (error) => {
          console.error('Cesium 加载失败:', error);
        };
        document.head.appendChild(script);
      }
    },

    initCesium() {
      console.log('开始初始化 Cesium...');
      
      try {
        // 初始化 Cesium 查看器
        this.viewer = new window.Cesium.Viewer("cesiumContainer", {
          terrain: window.Cesium.Terrain.fromWorldTerrain(),
          baseLayerPicker: true,
          geocoder: true,
          homeButton: true,
          sceneModePicker: true,
          navigationHelpButton: true,
          animation: true,
          timeline: true,
          fullscreenButton: true,
          infoBox: true,
          selectionIndicator: true,
        });

        console.log('Cesium 查看器创建成功');

        // 设置初始视角到中国
        this.viewer.camera.setView({
          destination: window.Cesium.Cartesian3.fromDegrees(116.4074, 39.9042, 1000000),
          orientation: {
            heading: 0.0,
            pitch: -window.Cesium.Math.PI_OVER_TWO,
            roll: 0.0
          }
        });

        console.log('初始视角设置完成');

        // 添加一个测试点来验证 Cesium 是否正常工作
        this.viewer.entities.add({
          position: window.Cesium.Cartesian3.fromDegrees(116.4074, 39.9042, 1000),
          point: { 
            pixelSize: 20, 
            color: window.Cesium.Color.RED,
            outlineColor: window.Cesium.Color.WHITE,
            outlineWidth: 2
          },
          label: {
            text: '测试点 - 北京',
            font: '14pt sans-serif',
            style: window.Cesium.LabelStyle.FILL_AND_OUTLINE,
            outlineWidth: 2,
            verticalOrigin: window.Cesium.VerticalOrigin.BOTTOM,
            pixelOffset: new window.Cesium.Cartesian2(0, -40)
          }
        });

        console.log('测试点添加完成');
        console.log('Cesium 初始化完成');

      } catch (error) {
        console.error('Cesium 初始化失败:', error);
      }
    },

    createAircraftEntity(aircraftId, aircraftData) {
      console.log(`创建飞机实体: ${aircraftId}`, aircraftData);
      
      try {
        // 创建飞机模型实体
        const entity = this.viewer.entities.add({
          id: aircraftId,
          name: aircraftData.name || aircraftId,
          position: window.Cesium.Cartesian3.fromDegrees(
            aircraftData.longitude,
            aircraftData.latitude,
            aircraftData.altitude
          ),
          // 使用简单的点来测试
          point: {
            pixelSize: 15,
            color: window.Cesium.Color.BLUE,
            outlineColor: window.Cesium.Color.WHITE,
            outlineWidth: 2,
            heightReference: window.Cesium.HeightReference.NONE
          },
          label: {
            text: aircraftData.name || aircraftId,
            font: '14pt sans-serif',
            style: window.Cesium.LabelStyle.FILL_AND_OUTLINE,
            outlineWidth: 2,
            verticalOrigin: window.Cesium.VerticalOrigin.BOTTOM,
            pixelOffset: new window.Cesium.Cartesian2(0, -40),
            fillColor: window.Cesium.Color.WHITE,
            outlineColor: window.Cesium.Color.BLACK
          }
        });

        this.aircraftEntities.set(aircraftId, entity);
        console.log(`飞机实体创建成功: ${aircraftId}`);
        return entity;
      } catch (error) {
        console.error(`创建飞机实体失败: ${aircraftId}`, error);
      }
    },

    createTrackEntity(aircraftId) {
      console.log(`创建轨迹实体: ${aircraftId}`);
      
      try {
        // 创建轨迹线实体
        const entity = this.viewer.entities.add({
          id: `track_${aircraftId}`,
          name: `${aircraftId} 轨迹`,
          polyline: {
            positions: new window.Cesium.CallbackProperty(() => {
              const aircraft = this.aircrafts[aircraftId];
              if (!aircraft || !aircraft.trackPoints) return [];
              
              return aircraft.trackPoints.map(point => 
                window.Cesium.Cartesian3.fromDegrees(point.longitude, point.latitude, point.altitude)
              );
            }, false),
            width: 3,
            material: window.Cesium.Color.YELLOW,
            clampToGround: false
          }
        });

        this.trackEntities.set(aircraftId, entity);
        console.log(`轨迹实体创建成功: ${aircraftId}`);
        return entity;
      } catch (error) {
        console.error(`创建轨迹实体失败: ${aircraftId}`, error);
      }
    },

    toggleConnection() {
      if (this.isConnected) {
        this.disconnectWebSocket();
      } else {
        this.connectWebSocket();
      }
    },

    connectWebSocket() {
      try {
        console.log(`正在连接到: ${this.wsUrl}`);
        this.ws = new WebSocket(this.wsUrl);
        
        this.ws.onopen = () => {
          console.log('WebSocket 连接已建立');
          this.isConnected = true;
        };
        
        this.ws.onmessage = (event) => {
          const data = JSON.parse(event.data);
          console.log('收到 WebSocket 数据:', data);
          this.handleWebSocketMessage(data);
        };
        
        this.ws.onclose = () => {
          console.log('WebSocket 连接已关闭');
          this.isConnected = false;
        };
        
        this.ws.onerror = (error) => {
          console.error('WebSocket 错误:', error);
          this.isConnected = false;
        };
      } catch (error) {
        console.error('连接失败:', error);
        this.isConnected = false;
      }
    },

    disconnectWebSocket() {
      if (this.ws) {
        this.ws.close();
        this.ws = null;
      }
      this.isConnected = false;
      this.aircrafts = {};
      this.totalTrackPoints = 0;
      console.log('WebSocket 已断开');
    },

    handleWebSocketMessage(data) {
      console.log('处理 WebSocket 消息:', data.type);
      
      switch (data.type) {
        case 'init':
          this.handleInitData(data.aircrafts);
          break;
        case 'update':
          this.handleUpdateData(data.aircrafts);
          break;
        default:
          console.log('未知消息类型:', data.type);
      }
    },

    handleInitData(aircraftsData) {
      console.log('处理初始数据:', aircraftsData.length, '架飞机');
      
      // 清除现有实体
      this.clearAllEntities();
      
      // 创建所有飞机的实体
      aircraftsData.forEach(aircraftData => {
        this.createAircraftEntity(aircraftData.aircraftId, aircraftData);
        this.createTrackEntity(aircraftData.aircraftId);
        this.updateAircraftData(aircraftData);
      });

      // 缩放到飞机
      if (aircraftsData.length > 0) {
        this.viewer.zoomTo(this.viewer.entities);
      }
    },

    handleUpdateData(aircraftsData) {
      aircraftsData.forEach(aircraftData => {
        this.updateAircraftData(aircraftData);
        this.updateAircraftPosition(aircraftData);
      });
    },

    updateAircraftData(aircraftData) {
      const aircraftId = aircraftData.aircraftId;
      
      // 更新飞机数据
      this.aircrafts[aircraftId] = {
        ...aircraftData,
        position: `${aircraftData.latitude.toFixed(4)}, ${aircraftData.longitude.toFixed(4)}, ${aircraftData.altitude.toFixed(0)}m`
      };
      
      // 计算总轨迹点数
      this.totalTrackPoints = Object.values(this.aircrafts).reduce((total, aircraft) => {
        return total + (aircraft.trackPoints ? aircraft.trackPoints.length : 0);
      }, 0);
    },

    updateAircraftPosition(aircraftData) {
      const aircraftId = aircraftData.aircraftId;
      const entity = this.aircraftEntities.get(aircraftId);
      
      if (!entity) {
        console.warn(`飞机实体不存在: ${aircraftId}`);
        return;
      }
      
      const position = window.Cesium.Cartesian3.fromDegrees(
        aircraftData.longitude,
        aircraftData.latitude,
        aircraftData.altitude
      );
      
      // 更新飞机位置
      entity.position = position;
      
      // 更新标签位置
      entity.label.position = position;
      
      console.log(`更新飞机位置: ${aircraftId} - ${aircraftData.longitude.toFixed(4)}, ${aircraftData.latitude.toFixed(4)}, ${aircraftData.altitude.toFixed(0)}m`);
    },

    clearAllEntities() {
      console.log('清除所有实体');
      
      // 清除所有飞机实体
      this.aircraftEntities.forEach(entity => {
        this.viewer.entities.remove(entity);
      });
      this.aircraftEntities.clear();
      
      // 清除所有轨迹实体
      this.trackEntities.forEach(entity => {
        this.viewer.entities.remove(entity);
      });
      this.trackEntities.clear();
      
      console.log('实体清除完成');
    }
  }
};
</script>

<style scoped>
.control-panel {
  position: absolute;
  top: 10px;
  left: 10px;
  background: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 15px;
  border-radius: 5px;
  z-index: 1000;
  font-family: Arial, sans-serif;
  max-width: 300px;
  max-height: 80vh;
  overflow-y: auto;
}

.control-panel button {
  background: #4CAF50;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 3px;
  cursor: pointer;
  margin-bottom: 10px;
  font-size: 14px;
  width: 100%;
}

.control-panel button:hover {
  background: #45a049;
}

.control-panel button.connected {
  background: #f44336;
}

.control-panel button.connected:hover {
  background: #da190b;
}

.status {
  margin-bottom: 10px;
  font-weight: bold;
}

.aircraft-list {
  margin-bottom: 10px;
}

.aircraft-list h4 {
  margin: 0 0 8px 0;
  font-size: 14px;
}

.aircraft-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 4px 0;
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
  font-size: 12px;
}

.aircraft-item:last-child {
  border-bottom: none;
}

.position {
  font-size: 10px;
  color: #ccc;
  text-align: right;
}

.info {
  font-size: 12px;
  line-height: 1.4;
  color: #ccc;
}
</style>